﻿// ------------------------------------------------------------------------------------
//      Copyright (c) uhavemyword@gmail.com. All rights reserved.
//      Created by Ben at 2/20/2013 3:54:01 PM
// ------------------------------------------------------------------------------------

namespace CP.NLayer.Service.Services
{
    using CP.NLayer.Models.Business;
    using CP.NLayer.Models.Entities;
    using CP.NLayer.Service.Contracts;
    using Microsoft.Practices.Unity;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;

    [ErrorHandlingBehavior]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class UserDisplayModelService : IUserDisplayModelService
    {
        #region IDisplayModelService<UserDisplayModel>
        public int GetCount()
        {
            var service = DependencyInjection.Container.Resolve<IUserService>();
            return service.GetCount();
        }

        public IList<UserDisplayModel> GetPage(int pageIndex, int pageSize)
        {
            var service = DependencyInjection.Container.Resolve<IUserService>();
            var users = service.GetPage(pageIndex, pageSize);
            return BuildModels(users);
        }

        public void Delete(UserDisplayModel obj)
        {
            var service = DependencyInjection.Container.Resolve<IUserService>();
            service.DeleteById(GetId(obj));
        }

        public string GetId(UserDisplayModel obj)
        {
            return obj.Id;
        }
        #endregion

        private UserDisplayModel BuildModel(User user)
        {
            if (user == null)
            {
                return null;
            }

            return new UserDisplayModel()
            {
                Id = user.Id,
                FullName = user.FullName,
                LoginName = user.LoginName,
                IsActive = user.IsActive,
                RoleNames = string.Join(", ", user.Roles.Select(x => x.Name))
            };
        }

        private IList<UserDisplayModel> BuildModels(IList<User> users)
        {
            if (users == null)
            {
                return null;
            }
            var list = new List<UserDisplayModel>();
            foreach (var obj in users)
            {
                list.Add(BuildModel(obj));
            }
            return list;
        }
    }
}
